<template>
    <div>
        <input v-show="false" ref="upload-file" type="file" :multiple="multiple" @change="getUploadFile" />
        <el-button :type="type" :class="icon" :size="size" :disabled="disabled" v-bind="extraAttrs" @click="$refs['upload-file'].click()">{{label}}</el-button>
    </div>
</template>

<script>
export default {
    // 除以下字段外，支持el-button的所有参数
    props: {
        multiple: Boolean, // 是否支持选择多个文件
        label: { // 按钮文本
            type: String,
            default: '导入'
        },
        type: { // primary / success / warning / danger / info / text
            type: String,
            default: 'primary'
        },
        icon: {
            type: String,
            default: ''
        },
        size: { // medium / small / mini
            type: String,
            default: ''
        },
        suffix: { // 支持的文件类型后缀,传空表示不限制文件类型 eg.['xlsx', 'xls']
            type: Array,
            default: () => []
        },
        disabled: Boolean
    },
    computed: {
        extraAttrs () {
            let { multiple, label, type, icon, size, suffix, disabled, ...rest } = this.$attrs
            return rest
        }
    },
    methods: {
        getUploadFile (event) {
            let ref = this.$refs['upload-file']
            let files = Array.from(event.target.files)
            ref.value = ''
            if (files.length) {
                let suffixAvailable = this.suffixValidate(files, this.suffix)
                if (!suffixAvailable) return
                this.$emit('upload', this.multiple ? files : files[0])
            }
        },
        suffixValidate (filesList, suffixList) {
            if (!suffixList.length) { // 不限制文件类型
                return true
            }
            let suffixAvailable = true
            for (let i = 0; i < filesList.length; i++) {
                let arr = filesList[i].name.split('.')
                const fileSuffix = arr[arr.length - 1]
                if (!suffixList.includes(fileSuffix)) {
                    this.showNotify({ message: `只能上传类型为${this.suffix.join(',')}的文件!`, color: 'negative' })
                    suffixAvailable = false
                }
                if (!suffixAvailable) {
                    break
                }
            }
            return suffixAvailable
        }
    }
}
</script>
